#!/usr/bin/env node

require('dotenv').config();
const { Client } = require('basic-ftp');
const chalk = require('chalk');

async function simpleTest() {
    console.log(chalk.blue('🧪 简单FTP连接测试'));
    
    const client = new Client();
    
    // 禁用一些可能导致问题的特性
    client.ftp.verbose = true;
    client.ftp.timeout = 10000;
    client.ftp.passive = false; // 先尝试主动模式
    
    try {
        console.log(chalk.yellow('连接配置:'));
        console.log(`  主机: ${process.env.FTP_HOST}`);
        console.log(`  端口: ${process.env.FTP_PORT || 21}`);
        console.log(`  用户: ${process.env.FTP_USER}`);
        console.log(`  主动模式: true`);
        console.log(`  超时: 10s\n`);
        
        await client.access({
            host: process.env.FTP_HOST,
            port: parseInt(process.env.FTP_PORT) || 21,
            user: process.env.FTP_USER,
            password: process.env.FTP_PASSWORD,
            secure: false
        });
        
        console.log(chalk.green('✅ 连接成功!'));
        
        // 测试简单命令
        console.log(chalk.blue('测试目录列表...'));
        const list = await client.list();
        console.log(chalk.green(`✅ 目录列表成功，找到 ${list.length} 个项目`));
        
        // 测试工作目录
        const pwd = await client.pwd();
        console.log(chalk.green(`✅ 当前目录: ${pwd}`));
        
    } catch (error) {
        console.error(chalk.red('❌ 连接失败:'), error.message);
        
        // 尝试被动模式
        console.log(chalk.yellow('\n尝试被动模式...'));
        client.ftp.passive = true;
        
        try {
            await client.access({
                host: process.env.FTP_HOST,
                port: parseInt(process.env.FTP_PORT) || 21,
                user: process.env.FTP_USER,
                password: process.env.FTP_PASSWORD,
                secure: false
            });
            
            console.log(chalk.green('✅ 被动模式连接成功!'));
            
        } catch (passiveError) {
            console.error(chalk.red('❌ 被动模式也失败:'), passiveError.message);
        }
    } finally {
        client.close();
    }
}

simpleTest();